<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Inziu Iosevka Slab SC:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="标准线性回归">
<meta property="og:type" content="article">
<meta property="og:title" content="Linear Regression">
<meta property="og:url" content="http://idmk.oschina.io/2017/08/27/Linear-Regression/index.html">
<meta property="og:site_name" content="苦舟">
<meta property="og:description" content="标准线性回归">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://idmk.oschina.io/2017/08/27/Linear-Regression/markdown-img-paste-2017082723262983.png">
<meta property="og:image" content="http://idmk.oschina.io/2017/08/27/Linear-Regression/markdown-img-paste-20170828004316385.png">
<meta property="og:image" content="http://idmk.oschina.io/2017/08/27/Linear-Regression/markdown-img-paste-2017082800492212.png">
<meta property="og:image" content="http://idmk.oschina.io/2017/08/27/Linear-Regression/markdown-img-paste-20170828005348725.png">
<meta property="og:image" content="http://idmk.oschina.io/2017/08/27/Linear-Regression/markdown-img-paste-20170828092546842.png">
<meta property="og:updated_time" content="2017-11-22T15:33:54.078Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Linear Regression">
<meta name="twitter:description" content="标准线性回归">
<meta name="twitter:image" content="http://idmk.oschina.io/2017/08/27/Linear-Regression/markdown-img-paste-2017082723262983.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://idmk.oschina.io/2017/08/27/Linear-Regression/"/>





  <title>Linear Regression | 苦舟</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">苦舟</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学海无涯，吾将上下求索。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://idmk.oschina.io/2017/08/27/Linear-Regression/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="东木金">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苦舟">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Linear Regression</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-27T23:24:40+08:00">
                2017-08-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/ML/" itemprop="url" rel="index">
                    <span itemprop="name">ML</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>标准线性回归</p>
<a id="more"></a>
<h2 id="标准线性回归"><a href="#标准线性回归" class="headerlink" title="标准线性回归"></a>标准线性回归</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># Linear Regression</span></div><div class="line"></div><div class="line"><span class="comment">#%%</span></div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">load_dataset</span><span class="params">(filepath)</span>:</span></div><div class="line">    <span class="comment"># n_feat =</span></div><div class="line">    X = []</div><div class="line">    y = []</div><div class="line">    <span class="keyword">with</span> open(filepath, <span class="string">'r'</span>, encoding=<span class="string">"UTF-8"</span>) <span class="keyword">as</span> fr:</div><div class="line">        <span class="keyword">for</span> line <span class="keyword">in</span> fr.readlines():</div><div class="line">            row = line.split(<span class="string">"\t"</span>)</div><div class="line">            x = [float(cell) <span class="keyword">for</span> cell <span class="keyword">in</span> row]</div><div class="line">            X.append(x[<span class="number">0</span>: <span class="number">-1</span>])</div><div class="line">            y.append(x[<span class="number">-1</span>])</div><div class="line"></div><div class="line">    <span class="keyword">return</span> X, y</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">stand_regres</span><span class="params">(X, y)</span>:</span></div><div class="line">    x_mat = np.mat(X)</div><div class="line">    y_mat = np.mat(y).T</div><div class="line">    xTx = x_mat.T * x_mat</div><div class="line">    <span class="keyword">if</span> np.linalg.det(xTx) == <span class="number">0.0</span>:</div><div class="line">        print(<span class="string">"This matrix is singular, cannot do inverse"</span>)</div><div class="line">        <span class="keyword">return</span></div><div class="line">    ws = xTx.I * (x_mat.T * y_mat)</div><div class="line">    <span class="keyword">return</span> ws</div><div class="line"></div><div class="line"></div><div class="line">X, y = load_dataset(<span class="string">"./Ch08/ex0.txt"</span>)</div><div class="line">ws = stand_regres(X, y)</div><div class="line"></div><div class="line">print(ws)</div><div class="line">exit()</div><div class="line"></div><div class="line">x_mat = np.mat(X)</div><div class="line">x1_arr = x_mat[:, <span class="number">1</span>].flatten().A[<span class="number">0</span>]</div><div class="line">y_arr = np.array(y)</div><div class="line"></div><div class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</div><div class="line">fig = plt.figure()</div><div class="line">ax = fig.add_subplot(<span class="number">111</span>)</div><div class="line">ax.scatter(x1_arr, y_arr)</div><div class="line">range_min = x1_arr.min()</div><div class="line">range_max = x1_arr.max()</div><div class="line">inx = np.linspace(range_min, range_max, num=<span class="number">50</span>)</div><div class="line">ws = ws.flatten().A[<span class="number">0</span>]</div><div class="line">hypo = ws[<span class="number">0</span>] + ws[<span class="number">1</span>] * inx</div><div class="line">ax.plot(inx, hypo)</div><div class="line"></div><div class="line">plt.show()</div></pre></td></tr></table></figure>
<pre><code>[[ 3.00774324]
[ 1.69532264]]
</code></pre><img src="/2017/08/27/Linear-Regression/markdown-img-paste-2017082723262983.png" alt="markdown-img-paste-2017082723262983.png" title="">
<h2 id="预测向量与真实向量之间的相关性系数"><a href="#预测向量与真实向量之间的相关性系数" class="headerlink" title="预测向量与真实向量之间的相关性系数"></a>预测向量与真实向量之间的相关性系数</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># Linear Regression</span></div><div class="line"></div><div class="line"><span class="comment">#%%</span></div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">load_dataset</span><span class="params">(filepath)</span>:</span></div><div class="line">    <span class="comment"># n_feat =</span></div><div class="line">    X = []</div><div class="line">    y = []</div><div class="line">    <span class="keyword">with</span> open(filepath, <span class="string">'r'</span>, encoding=<span class="string">"UTF-8"</span>) <span class="keyword">as</span> fr:</div><div class="line">        <span class="keyword">for</span> line <span class="keyword">in</span> fr.readlines():</div><div class="line">            row = line.split(<span class="string">"\t"</span>)</div><div class="line">            x = [float(cell) <span class="keyword">for</span> cell <span class="keyword">in</span> row]</div><div class="line">            X.append(x[<span class="number">0</span>: <span class="number">-1</span>])</div><div class="line">            y.append(x[<span class="number">-1</span>])</div><div class="line"></div><div class="line">    <span class="keyword">return</span> X, y</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">stand_regres</span><span class="params">(X, y)</span>:</span></div><div class="line">    x_mat = np.mat(X)</div><div class="line">    y_mat = np.mat(y).T</div><div class="line">    xTx = x_mat.T * x_mat</div><div class="line">    <span class="keyword">if</span> np.linalg.det(xTx) == <span class="number">0.0</span>:</div><div class="line">        print(<span class="string">"This matrix is singular, cannot do inverse"</span>)</div><div class="line">        <span class="keyword">return</span></div><div class="line">    ws = xTx.I * (x_mat.T * y_mat)</div><div class="line">    <span class="keyword">return</span> ws</div><div class="line"></div><div class="line"></div><div class="line">X, y = load_dataset(<span class="string">"./Ch08/ex0.txt"</span>)</div><div class="line">ws = stand_regres(X, y)</div><div class="line"></div><div class="line"></div><div class="line">x_mat = np.mat(X)</div><div class="line">y_mat = np.mat(y)</div><div class="line">hypo = x_mat * ws</div><div class="line">np.corrcoef(hypo.T, y_mat)</div></pre></td></tr></table></figure>
<pre><code>array([[ 1.        ,  0.98647356],
       [ 0.98647356,  1.        ]])
</code></pre><p>说明：<br>hypo.T, y_mat 都是 1*m 的矩阵，<code>np.corrcoef(X, Y)</code> 要求大小相同的列向量，因此下方的代码也是正确的：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">np.corrcoef(hypo.T.flatten().A[<span class="number">0</span>], y_mat.flatten().A[<span class="number">0</span>])</div></pre></td></tr></table></figure></p>
<p>理解结果：<br>结果矩阵包含所有两两组合的相关系数。可以看到对角线上的数据是 1.0，因为自己与自己的的匹配是完美的，真是与假设的相关性系数为 0.98。</p>
<h2 id="局部加权线性回归"><a href="#局部加权线性回归" class="headerlink" title="局部加权线性回归"></a>局部加权线性回归</h2><p>数据分布很少完美地呈现线性，因此线性回归的一个问题是有可能出现欠拟合现象。所以有些方法允许在估计中引入一些偏差，从而降低预测的均方误差。</p>
<p>其中的一个方法是局部加权线性回归（Locally Weighted Linear Regression，为 LWLR）。在该算法中，我们给待预测点附近的每个点赋予一定的权重；然后在这个子集上基于最小均方差来进行普通的回归。与 kNN 一样，这种算法每次预测均需要事先选取出对应的数据子集。该算法解出回归系数 w 的形式如下：<br><img src="/2017/08/27/Linear-Regression/markdown-img-paste-20170828004316385.png" alt="markdown-img-paste-20170828004316385.png" title=""><br>其中 w 是一个矩阵，用来给每个数据点赋予权重。</p>
<p>LWLR 使用“核”（与支持向量机中的核类似）来对与被预测的样本的距离更近的样本赋予更高的权重。核的类型可以自由选择，最常用的核就是高斯核，高斯核对应的权重如下：<br><img src="/2017/08/27/Linear-Regression/markdown-img-paste-2017082800492212.png" alt="markdown-img-paste-2017082800492212.png" title=""><br>其中 x 是被预测的点。<br>注意区分这里的权重 W 和回归系数 w；与 kNN 一样，该加权模型认为样本点距离越近，越可能符合同一个线性模型。</p>
<p>这样就构建了一个只含对角元素的权重矩阵 w，并且点 x 与 x(i) 越近，w(i,i) 将会越大。上述公式包含一个需要用户指定的参数 k，它决定了对附近的点赋予多大的权重，这也是使用 LWLR 时唯一需要考虑的参数，在图 1 中可以看到参数 k 与权重的关系。<br><img src="/2017/08/27/Linear-Regression/markdown-img-paste-20170828005348725.png" alt="图 1 - 在不同的 k 下每个点的权重图（假定我们正预测的点是 x = 0.5）" title="图 1 - 在不同的 k 下每个点的权重图（假定我们正预测的点是 x = 0.5）"><br>最上面的图是原始数据集，第二个图显示了当 k = 0.5 时，大部分的数据都用于训练回归模型；而最下面的图显示当 k = 0.01 时，仅有很少的局部 点被用于训练回归模型。</p>
<h3 id="模型效果"><a href="#模型效果" class="headerlink" title="模型效果"></a>模型效果</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># Linear Regression</span></div><div class="line"></div><div class="line"><span class="comment">#%%</span></div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">load_dataset</span><span class="params">(filepath)</span>:</span></div><div class="line">    <span class="comment"># n_feat =</span></div><div class="line">    X = []</div><div class="line">    y = []</div><div class="line">    <span class="keyword">with</span> open(filepath, <span class="string">'r'</span>, encoding=<span class="string">"UTF-8"</span>) <span class="keyword">as</span> fr:</div><div class="line">        <span class="keyword">for</span> line <span class="keyword">in</span> fr.readlines():</div><div class="line">            row = line.split(<span class="string">"\t"</span>)</div><div class="line">            x = [float(cell) <span class="keyword">for</span> cell <span class="keyword">in</span> row]</div><div class="line">            X.append(x[<span class="number">0</span>: <span class="number">-1</span>])</div><div class="line">            y.append(x[<span class="number">-1</span>])</div><div class="line"></div><div class="line">    <span class="keyword">return</span> X, y</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">stand_regres</span><span class="params">(X, y)</span>:</span></div><div class="line">    x_mat = np.mat(X)</div><div class="line">    y_mat = np.mat(y).T</div><div class="line">    xTx = x_mat.T * x_mat</div><div class="line">    <span class="keyword">if</span> np.linalg.det(xTx) == <span class="number">0.0</span>:</div><div class="line">        print(<span class="string">"This matrix is singular, cannot do inverse"</span>)</div><div class="line">        <span class="keyword">return</span></div><div class="line">    ws = xTx.I * (x_mat.T * y_mat)</div><div class="line">    <span class="keyword">return</span> ws</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">lwlr</span><span class="params">(t, X, y, k=<span class="number">1.0</span>)</span>:</span></div><div class="line">    x_mat = np.mat(X)</div><div class="line">    y_mat = np.mat(y).T  <span class="comment"># 列向量</span></div><div class="line">    t_mat = np.mat(t)</div><div class="line">    m = x_mat.shape[<span class="number">0</span>]</div><div class="line">    weights = np.mat(np.eye((m)))</div><div class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> range(m):</div><div class="line">        diff_mat = t_mat - x_mat[j, :]</div><div class="line">        weights[j, j] = np.exp(diff_mat * diff_mat.T / (<span class="number">-2.0</span> * k ** <span class="number">2</span>))</div><div class="line">        <span class="comment"># 权重值大小以指数级衰减</span></div><div class="line">    xTx = x_mat.T * (weights) * x_mat</div><div class="line">    <span class="keyword">if</span> np.linalg.det(xTx) == <span class="number">0.0</span>:</div><div class="line">        print(<span class="string">"This matrix is singular, cannot do inverse"</span>)</div><div class="line">        <span class="keyword">return</span></div><div class="line">    ws = xTx.I * (x_mat.T * (weights * y_mat))</div><div class="line">    <span class="keyword">return</span> t_mat * ws</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">lwlr_test</span><span class="params">(t, X, y, k=<span class="number">1.0</span>)</span>:</span></div><div class="line">    m = len(t)</div><div class="line">    hypo = np.zeros(m)</div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(m):</div><div class="line">        hypo[i] = lwlr(t[i], X, y, k)</div><div class="line">    <span class="keyword">return</span> hypo</div><div class="line"></div><div class="line"></div><div class="line">X, y = load_dataset(<span class="string">"./Ch08/ex0.txt"</span>)</div><div class="line">ws = stand_regres(X, y)</div><div class="line"></div><div class="line">print(<span class="string">' 真实值 '</span>, y[<span class="number">0</span>])</div><div class="line">print(<span class="string">' 在 k = 1.0 时的预测值 '</span>, lwlr(X[<span class="number">0</span>], X, y, <span class="number">1.0</span>))</div><div class="line">print(<span class="string">' 在 k = 0.1 时的预测值 '</span>, lwlr(X[<span class="number">0</span>], X, y, <span class="number">0.1</span>))</div><div class="line">print(<span class="string">' 在 k = 0.01 时的预测值 '</span>, lwlr(X[<span class="number">0</span>], X, y, <span class="number">0.01</span>))</div><div class="line">print(<span class="string">' 在 k = 0.003 时的预测值 '</span>, lwlr(X[<span class="number">0</span>], X, y, <span class="number">0.003</span>))</div><div class="line"></div><div class="line">x_mat = np.mat(X)</div><div class="line">srt_idx = x_mat[:, <span class="number">1</span>].argsort(<span class="number">0</span>)</div><div class="line">x_sort = x_mat[srt_idx][:, <span class="number">0</span>, :]</div><div class="line"></div><div class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</div><div class="line">fig = plt.figure()</div><div class="line">ax = fig.add_subplot(<span class="number">111</span>)</div><div class="line">hypo = lwlr_test(X, X, y, <span class="number">1.0</span>)</div><div class="line">ax.plot(x_sort[:, <span class="number">1</span>], hypo[srt_idx], c=<span class="string">'yellow'</span>)</div><div class="line">hypo = lwlr_test(X, X, y, <span class="number">0.01</span>)</div><div class="line">ax.plot(x_sort[:, <span class="number">1</span>], hypo[srt_idx], c=<span class="string">'blue'</span>)</div><div class="line">hypo = lwlr_test(X, X, y, <span class="number">0.003</span>)</div><div class="line">ax.plot(x_sort[:, <span class="number">1</span>], hypo[srt_idx], c=<span class="string">'red'</span>)</div><div class="line">ax.scatter(x_mat[:, <span class="number">1</span>].flatten().A[<span class="number">0</span>], np.array(y), s=<span class="number">2</span>, c=<span class="string">'black'</span>)</div><div class="line">plt.show()</div></pre></td></tr></table></figure>
<pre><code>真实值 3.176513
在 k = 1.0 时的预测值 [[ 3.12204471]]
在 k = 0.1 时的预测值 [[ 3.14971201]]
在 k = 0.01 时的预测值 [[ 3.20366661]]
在 k = 0.003 时的预测值 [[ 3.20200665]]
</code></pre><img src="/2017/08/27/Linear-Regression/markdown-img-paste-20170828092546842.png" alt="图 2 - k 取不同值时不同的拟合效果" title="图 2 - k 取不同值时不同的拟合效果">
<p>当 k = 1.0 时权重很大，如同将所有的数据视为等权重，得出的最佳拟合直线与标准的回归一致。 k = 0.01 得到了非常好的效果， 抓住了数据的潜在模式。下图使用 k = 0.003 纳入了太多的噪声点，拟合的直线与数据点过于贴近，存在过拟合的问题。</p>
<p>局部加权线性回归也存在一个问题，即增加了计算量，因为它对每个点做预测时都必须使用整个数据集。从图 2 可以看出，k = 0.01 时可以得到很好的估计，但是同时看一下图 1 中 k = 0.01 的情况，就会发现大多数据点的权重都接近零。如果避免这些计算将可以减少程序运行时间，从而缓解因计算量增加带来的问题。<br>我们可以直接对离被预测点距离大于 d 的点的权重赋予 0 ，只计算离被预测点距离小于等于 d 的点的权重。</p>
<h2 id="What-if-we-have-more-features-than-data-points"><a href="#What-if-we-have-more-features-than-data-points" class="headerlink" title="What if we have more features than data points?"></a>What if we have more features than data points?</h2><p>What if we have more features than data points? Can we still make a prediction using linear regression and the methods we ’ ve seen already? Then answer is no, not using the methods we ’ ve seen already. The reason for this is that when we try to compute $(X^{T}X)^{-1}$ we ’ ll get an error. If we have more features than data points (n&gt;m), we say that our data matrix X isn ’ tfull rank. When the data isn ’ t full rank, we ’ ll have a difficult time computing the inverse.</p>
<p>To solve this problem, statisticians introduced the concept of ridge regression. We ’ ll then discuss the lasso, which is better but difficult to compute. We ’ ll finally examine a second shrinkage method called forward stagewise regression, which is an easy way to approximate the lasso.</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/27/Regular-Expression/" rel="next" title="Regular Expression">
                <i class="fa fa-chevron-left"></i> Regular Expression
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/28/Tree-Based-Regression/" rel="prev" title="Tree Based Regression（树回归）">
                Tree Based Regression（树回归） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="东木金" />
          <p class="site-author-name" itemprop="name">东木金</p>
           
              <p class="site-description motion-element" itemprop="description">正在学习机器学习，希望能变得很强！</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">162</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">18</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">42</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bdmk" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:catcherchan94@outlook.com" target="_blank" title="E-Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i>
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#标准线性回归"><span class="nav-number">1.</span> <span class="nav-text">标准线性回归</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#预测向量与真实向量之间的相关性系数"><span class="nav-number">2.</span> <span class="nav-text">预测向量与真实向量之间的相关性系数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#局部加权线性回归"><span class="nav-number">3.</span> <span class="nav-text">局部加权线性回归</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#模型效果"><span class="nav-number">3.1.</span> <span class="nav-text">模型效果</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#What-if-we-have-more-features-than-data-points"><span class="nav-number">4.</span> <span class="nav-text">What if we have more features than data points?</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">东木金</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'manual') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
